#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "filterapi.h"
#include "filter.h"
#include "filterprocess.h"

#define FILTERAPI_DEBUG(fmt, ...) //SM_Printf(fmt, ##__VA_ARGS__)

int Filter_StartPidFilter (filter_pid_param_t* pstParam, filter_handle_t *phFilter)
{
	int rc = 0;

	FILTERAPI_DEBUG("Filter_StartPidFilter entry, pstParam = %p, phFilter = %p\r\n", pstParam, phFilter);
	rc = Filter_AllocPidFilter(phFilter, pstParam->m_u16Pid);
	if(rc == 0)
	{
		Filter_SetPidNotify(*phFilter, pstParam->m_pfCallback);
		rc = Filter_EnablePidFilter(*phFilter);
	}

	FILTERAPI_DEBUG("Filter_StartPidFilter return rc = %d\r\n", rc);
	return rc;
}

int Filter_StopPidFilter (filter_handle_t hFilter)
{
	int rc = 0;

	FILTERAPI_DEBUG("Filter_StopPidFilter entry, hFilter = %d\r\n", hFilter);
	rc = Filter_DisablePidFilter(hFilter);
	if(rc == 0)
		rc = Filter_FreePidFilter(hFilter);
	FILTERAPI_DEBUG("Filter_StopPidFilter return rc = %d\r\n", rc);
	return rc;
}

int Filter_StartSectionFilter (filter_section_param_t* pstParam, filter_handle_t*phFilter)
{
	unsigned int hFilter;
	unsigned char au8Mask[MAX_SEC_FILTER_DEPTH];
	unsigned char au8Data[MAX_SEC_FILTER_DEPTH];
	int ret;
	unsigned int i;

	FILTERAPI_DEBUG("Filter_StartSectionFilte entry, pstParam = %p, phFilter = %p\r\n", pstParam, phFilter);
	if(!pstParam)
	{
		return -1;
	}

	memset(au8Mask, 0, MAX_SEC_FILTER_DEPTH);
	memset(au8Data, 0, MAX_SEC_FILTER_DEPTH);

	ret = Filter_AllocSectionFilter(&hFilter, pstParam->m_u16Pid);
	if (hFilter == INVALID_FILTER_HANDLE)	
		return -1;
	Filter_SetSectionNotify(hFilter, pstParam->m_pfCallback, NULL);	

	if(pstParam->m_pu16SectByte != NULL)
	{
		for(i=0;i<MAX_SEC_FILTER_DEPTH;i++)
		{
			au8Mask[i] = (pstParam->m_pu16SectByte[i]>>8);
			au8Data[i] = (pstParam->m_pu16SectByte[i] & 0xFF); 
		}
	}	
	ret = Filter_SetSectionMask(hFilter, au8Mask, au8Data, MAX_SEC_FILTER_DEPTH);
	ret = Filter_SetCrcCheck(hFilter, pstParam->m_u8CrcCheck);
	ret = Filter_EnableSectionFilter(hFilter);

	*phFilter = hFilter;

	FILTERAPI_DEBUG("Filter_StartSectionFilte return rc = %d\r\n", ret);
	return ret;
}

int Filter_StopSectionFilter (filter_handle_t hFilter)
{
	int rc;

	FILTERAPI_DEBUG("Filter_StopSectionFilter entry, hFilter = %d, phFilter = %p\r\n", hFilter);
	rc = Filter_DisableSectionFilter(hFilter);
	if(rc == 0)
		rc = Filter_FreeSectionFilter(hFilter);
	FILTERAPI_DEBUG("Filter_StopSectionFilter return rc = %d\r\n", rc);
	return rc;
}

int Filter_Init()
{
	FILTERAPI_DEBUG("Filter_Init entry\r\n");
	Filter_Initialize();
	Filter_Start();
	FILTERAPI_DEBUG("Filter_Init return 0\r\n");
	return 0;
}